<template>
  <div class="spot-detail-container">
    <!-- 固定的顶部header -->
    <div class="header">
      <!-- 返回按钮保持在左边 -->
      <button class="back-btn" @click="goBack">
        ← 返回列表
      </button>
      
      <!-- 居中的操作区域 -->
      <div class="header-actions">
        <button class="secondary-btn" @click="viewFavorites">
          收藏列表
        </button>
        <button class="secondary-btn" @click="viewVisits">
          访问列表
        </button>
        <button class="secondary-btn" @click="openOnMap">
          在地图上查看
        </button>
        <span class="separator">|</span>
        <button class="secondary-btn" @click="updateSpot">
          更新
        </button>
        <button class="secondary-btn" @click="loadSpotDetail">
          刷新
        </button>
        <button :class="['toggle-btn', isDisabled ? 'disabled' : 'enabled']" @click="toggleDisable">
          {{ isDisabled ? '禁用' : '启用' }}
        </button>
      </div>
    </div>

    <!-- 可滚动的内容区域 -->
    <div class="scrollable-content">
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <div class="loading-spinner"></div>
        <p>正在加载钓点详情...</p>
      </div>

      <!-- 错误状态 -->
      <div v-else-if="error" class="error-container">
        <div class="error-icon">⚠️</div>
        <p>{{ error }}</p>
        <button class="retry-btn" @click="loadSpotDetail">
          重新加载
        </button>
      </div>

      <!-- 详情内容 -->
      <div v-else-if="spot" class="detail-content">
        <!-- 组1：图片展示CARD -->
        <div class="card image-card" v-if="spot.pics && spot.pics.length > 0">
          <div class="card-header">
            <h3>钓点图片</h3>
          </div>
          <div class="card-content">
            <!-- 大图显示 -->
            <div class="main-image-container">
              <img :src="currentMainImage" :alt="spot.name" class="main-image" @error="$event.target.src = '/placeholder-image.jpg'" />
            </div>
            <!-- 横向小图列表 -->
            <div class="thumbnail-list">
              <img 
                v-for="(pic, index) in spot.pics" 
                :key="index"
                :src="pic" 
                :alt="`缩略图 ${index + 1}`"
                :class="['thumbnail', { active: currentMainImage === pic }]"
                @click="currentMainImage = pic"
                @error="$event.target.src = '/placeholder-image.jpg'"
              />
            </div>
          </div>
        </div>

        <!-- 组2：基本信息CARD -->
        <div class="card info-card">
          <div class="card-header">
            <h3>基本信息</h3>
          </div>
          <div class="card-content">
              <!-- 钓点名称单独一行 -->
              <div class="spot-name-row">
                <h2 class="spot-name">{{ spot.name }}</h2>
              </div>

              <!-- 其他信息4列显示，改为label:value横向显示 -->
              <div class="info-grid-4-col">
                <div class="info-item">
                  <span class="info-label">水域类型:</span>
                  <span class="info-value">{{ spot.waterType.name }}</span>
                </div>
                <div class="info-item">
                  <span class="info-label">等级:</span>
                  <span class="info-value level-badge" :class="`level-${spot.lvl.code}`">
                    {{ spot.lvl.name }}
                  </span>
                </div>
                <div class="info-item">
                  <span class="info-label">坐标:</span>
                  <span class="info-value">{{ spot.location.latitude.toFixed(6) }}, {{ spot.location.longitude.toFixed(6) }}</span>
                </div>
                <div class="info-item">
                  <span class="info-label">距离:</span>
                  <span class="info-value">{{ spot.distance.name }}</span>
                </div>
                <div class="info-item">
                  <span class="info-label">创建者:</span>
                  <span class="info-value">{{ spot.createdByName }}</span>
                </div>
                <div class="info-item">
                  <span class="info-label">更新时间:</span>
                  <span class="info-value">{{ formatDate(spot.updatedAt) }}</span>
                </div>
                <div class="info-item">
                  <span class="info-label">是否免费:</span>
                  <span :class="['info-value', 'status-badge', spot.isFree === 1 ? 'free' : 'paid']">
                    {{ spot.isFree === 1 ? '免费' : '收费' }}
                  </span>
                </div>
                <div class="info-item">
                  <span class="info-label">是否私密:</span>
                  <span :class="['info-value', 'status-badge', spot.secret === 1 ? 'private' : 'public']">
                    {{ spot.secret === 1 ? '私密' : '公开' }}
                  </span>
                </div>
                <div class="info-item">
                  <span class="info-label">停车便利:</span>
                  <span :class="['info-value', 'status-badge', spot.parkingEasy === 1 ? 'convenient' : 'inconvenient']">
                    {{ spot.parkingEasy === 1 ? '便利' : '不便' }}
                  </span>
                </div>
              </div>
            </div>
        </div>

        <!-- 组3：分类信息CARD -->
        <div class="card category-card">
          <div class="card-header">
            <h3>分类信息</h3>
          </div>
          <div class="card-content">
            <!-- 钓点类型 -->
            <div class="category-item">
              <span class="category-label">钓点类型:</span>
              <span class="category-value">{{ spot.spotTypes.map(t => t.name).join(', ') }}</span>
            </div>
            
            <!-- 鱼种信息 -->
            <div class="category-item">
              <span class="category-label">鱼种信息:</span>
              <span class="category-value">{{ spot.fishTypes.map(f => f.name).join(', ') }}</span>
            </div>
          </div>
        </div>

        <!-- 组4：描述信息CARD -->
        <div class="card description-card">
          <div class="card-header">
            <h3>描述信息</h3>
          </div>
          <div class="card-content">
            <p class="description-text">{{ spot.description || '暂无描述信息' }}</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { invoke } from '@tauri-apps/api/core'

interface DistanceType {
  code: string
  name: string
  type: number
}

interface WaterType {
  code: string
  name: string
  type: number
}

interface LvlType {
  code: string
  name: string
  type: number
}

interface FishType {
  code: string
  name: string
  type: number
}

interface SpotType {
  code: string
  name: string
  type: number
}

interface Location {
  latitude: number
  longitude: number
}

interface FishingSpot {
  id: string
  name: string
  description: string
  location: Location
  waterType: WaterType
  lvl: LvlType
  fishTypes: Array<FishType>
  spotTypes: Array<SpotType>
  isFree: number
  secret: number
  parkingEasy: number
  disabled: number
  distance: DistanceType
  pics: Array<string>
  createdBy: string
  createdByName: string
  updatedAt: string
}

const router = useRouter()
const route = useRoute()

const spot = ref<FishingSpot | null>(null)
const loading = ref(true)
const error = ref('')
const currentMainImage = ref('')
const isDisabled = ref(false)

const spotId = computed(() => {
  const id = route.params.id
  return typeof id === 'string' ? id : id[0]
})

const loadSpotDetail = async () => {
  if (!spotId.value) {
    error.value = '无效的钓点ID'
    return
  }

  loading.value = true
  error.value = ''

  try {
    const response = await invoke('get_fishing_spot_by_id', { id: spotId.value })
    spot.value = response as FishingSpot
    // 设置默认主图为第一张图片
    if (spot.value.pics && spot.value.pics.length > 0) {
      currentMainImage.value = spot.value.pics[0]
    }
    // 设置禁用状态
    isDisabled.value = spot.value.disabled === 1
  } catch (err) {
    console.error('获取钓点详情失败:', err)
    error.value = '获取钓点详情失败，请稍后重试'
  } finally {
    loading.value = false
  }
}

const goBack = () => {
  router.back()
}

const openOnMap = () => {
    const {location, name} = JSON.parse(JSON.stringify(spot.value))
    const event = new CustomEvent('toggle-map-mode', {
    detail: { isMapMode: true, modeHandler: 'SpotDetail',data:{location,name} }

  })
  window.dispatchEvent(event)
  console.log('钓点详情页切换到地图模式，事件已发送')
  
}

const changeMainImage = (imageUrl: string) => {
  currentMainImage.value = imageUrl
}

const toggleDisable = async () => {
  if (!spotId.value) {
    window.showToast?.('无效的钓点ID', 'error')
    return
  }

  const newDisabledState = !isDisabled.value
  
  try {
    const result = await invoke('toggle_spot_disabled', {
      spotId: spotId.value,
      disabled: newDisabledState
    })

    // 直接使用我们请求的新状态，而不是依赖服务器返回
    isDisabled.value = newDisabledState
    
    // 同时更新spot对象的disabled值，保持一致性
    if (spot.value) {
      spot.value.disabled = newDisabledState ? 1 : 0
    }
    
    const message = newDisabledState ? '钓点已禁用' : '钓点已启用'
    window.showToast?.(message, 'success')
  } catch (error) {
    console.error('切换钓点状态失败:', error)
    window.showToast?.(error.toString() || '网络错误，请检查网络连接', 'error')
  }
}

const viewFavorites = () => {
  router.push({ name: 'Favorites', query: { spotId: spotId.value } })
}

const viewVisits = () => {
  router.push({ name: 'Visits', query: { spotId: spotId.value } })
}

const updateSpot = () => {
  router.push({ name: 'UpdateSpot', params: { id: spotId.value } })
}

const viewCircle = () => {
  router.push({ name: 'CircleDetail', params: { id: spotId.value } })
}

const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

onMounted(() => {
  loadSpotDetail()
})
</script>

<style scoped>
.spot-detail-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  color: #ffffff;
  background: #1e1e1e;
  overflow: hidden;
}

.header {
  position: sticky;
  top: 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 24px;
  background: rgba(30, 30, 35, 0.95);
  backdrop-filter: blur(12px);
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  z-index: 100;
  flex-shrink: 0;
}

.back-btn {
  background: rgba(29, 185, 84, 0.2);
  color: #1db954;
  border: 1px solid #1db954;
  padding: 8px 16px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s ease;
  white-space: nowrap;
}

.back-btn:hover {
  background: rgba(29, 185, 84, 0.3);
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 12px;
  flex: 1;
  justify-content: center;
}

.header-actions .primary-btn,
.header-actions .secondary-btn {
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  font-weight: 600;
  border-radius: 18px;
  transition: all 0.3s ease;
  white-space: nowrap;
  border: none;
  background: transparent;
  outline: none;
  font-family: inherit;
  cursor: pointer;
}

.header-actions .primary-btn {
  background: #1db954;
  color: #000;
  padding: 0 20px;
}

.header-actions .primary-btn:hover:not(:disabled) {
  background: #1ed760;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(29, 185, 84, 0.3);
}

.header-actions .secondary-btn {
  background: transparent;
  color: #b3b3b3;
  border: 1px solid rgba(255, 255, 255, 0.3);
  padding: 0 20px;
}

.header-actions .secondary-btn:hover:not(:disabled) {
  background: rgba(255, 255, 255, 0.1);
  color: #ffffff;
  border-color: rgba(255, 255, 255, 0.5);
}

.toggle-btn {
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  font-weight: 600;
  border-radius: 18px;
  transition: all 0.3s ease;
  white-space: nowrap;
  border: 1px solid rgba(255, 255, 255, 0.2);
  outline: none;
  font-family: inherit;
  cursor: pointer;
  padding: 0 20px;
}

.toggle-btn.enabled {
  background: #1db954;
  color: #ffffff;
  border-color: #1db954;
}

.toggle-btn.enabled:hover:not(:disabled) {
  background: #1ed760;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(29, 185, 84, 0.3);
}

.toggle-btn.disabled {
  background: #ff4444;
  color: #fff;
  border-color: #ff4444;
}

.toggle-btn.disabled:hover:not(:disabled) {
  background: #ff5555;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(255, 68, 68, 0.3);
}

.separator {
  color: rgba(255, 255, 255, 0.3);
  font-size: 16px;
  margin: 0 8px;
  display: flex;
  align-items: center;
  user-select: none;
}

/* 加载状态 */
.loading-container,
.error-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 400px;
  color: #b3b3b3;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 3px solid rgba(29, 185, 84, 0.3);
  border-top: 3px solid #1db954;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

.error-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.retry-btn {
  padding: 8px 16px;
  background: rgba(29, 185, 84, 0.2);
  color: #1db954;
  border: 1px solid #1db954;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.retry-btn:hover {
  background: rgba(29, 185, 84, 0.3);
}

/* 可滚动内容区域 */
.scrollable-content {
  flex: 1;
  overflow-y: auto;
  padding: 24px;
  padding-bottom: 48px;
  max-width: 1200px;
  margin: 0 auto;
  width: 100%;
  box-sizing: border-box;
}

.scrollable-content::-webkit-scrollbar {
  width: 8px;
}

.scrollable-content::-webkit-scrollbar-track {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 4px;
}

.scrollable-content::-webkit-scrollbar-thumb {
  background: rgba(29, 185, 84, 0.5);
  border-radius: 4px;
}

.scrollable-content::-webkit-scrollbar-thumb:hover {
  background: rgba(29, 185, 84, 0.7);
}

/* 详情内容 */
.detail-content {
  width: 100%;
}

.info-section {
  width: 100%;
}

.info-header {
  margin-bottom: 24px;
}

.spot-title {
  font-size: 32px;
  font-weight: bold;
  color: #ffffff;
  margin: 0;
}

.meta-info {
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin-bottom: 32px;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.info-item .label {
  font-size: 14px;
  color: #b3b3b3;
  font-weight: 600;
  min-width: 80px;
}

.info-item .value {
  font-size: 14px;
  color: #ffffff;
}

.section {
  margin-bottom: 32px;
}

.section h3 {
  font-size: 18px;
  font-weight: bold;
  color: #1db954;
  margin: 0 0 16px 0;
}

.tag-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.tag {
  background: rgba(29, 185, 84, 0.2);
  color: #1ed760;
  border: 1px solid #1db954;
  border-radius: 16px;
  padding: 6px 12px;
  font-size: 12px;
  font-weight: 600;
}

.facility-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
}

.facility-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 8px;
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.facility-label {
  font-size: 14px;
  color: #b3b3b3;
}

.status-badge {
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.status-badge.free {
  background: rgba(29, 185, 84, 0.2);
  color: #1ed760;
  border: 1px solid #1db954;
}

.status-badge.paid {
  background: rgba(255, 165, 0, 0.2);
  color: #ffa500;
  border: 1px solid #ffa500;
}

.status-badge.private {
  background: rgba(255, 68, 68, 0.2);
  color: #ff6666;
  border: 1px solid #ff6666;
}

.status-badge.public {
  background: rgba(29, 185, 84, 0.2);
  color: #1ed760;
  border: 1px solid #1db954;
}

.status-badge.forbidden {
  background: rgba(255, 68, 68, 0.2);
  color: #ff6666;
  border: 1px solid #ff6666;
}

.status-badge.allowed {
  background: rgba(29, 185, 84, 0.2);
  color: #1ed760;
  border: 1px solid #1db954;
}

.status-badge.convenient {
  background: rgba(29, 185, 84, 0.2);
  color: #1ed760;
  border: 1px solid #1db954;
}

.status-badge.inconvenient {
  background: rgba(255, 165, 0, 0.2);
  color: #ffa500;
  border: 1px solid #ffa500;
}

.level-badge {
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.level-badge.level-A {
  background: rgba(29, 185, 84, 0.2);
  color: #1ed760;
  border: 1px solid #1db954;
}

.level-badge.level-B {
  background: rgba(255, 255, 0, 0.2);
  color: #ffff00;
  border: 1px solid #ffff00;
}

.level-badge.level-C {
  background: rgba(255, 165, 0, 0.2);
  color: #ffa500;
  border: 1px solid #ff6666;
}

.level-badge.level-D {
  background: rgba(255, 68, 68, 0.2);
  color: #ff6666;
  border: 1px solid #ff6666;
}

.image-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 12px;
}

.spot-image {
  width: 100%;
  height: 150px;
  object-fit: cover;
  border-radius: 8px;
  border: 1px solid rgba(255, 255, 255, 0.1);
}

/* CARD样式 */
.card {
  background: rgba(40, 40, 45, 0.8);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 12px;
  margin-bottom: 16px;
  overflow: hidden;
}

.card-header {
  padding: 16px 20px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  background: rgba(30, 30, 35, 0.5);
}

.card-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #ffffff;
}

.card-content {
  padding: 20px;
}

/* 图片CARD样式 */
.image-card .card-content {
  padding: 0;
}

.main-image-container {
  width: 100%;
  height: 300px;
  background: #2a2a2a;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}

.main-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.thumbnail-list {
  display: flex;
  gap: 8px;
  padding: 12px;
  overflow-x: auto;
  background: rgba(30, 30, 35, 0.3);
  border-top: 1px solid rgba(255, 255, 255, 0.1);
}

.thumbnail {
  width: 80px;
  height: 60px;
  object-fit: cover;
  border-radius: 6px;
  cursor: pointer;
  border: 2px solid transparent;
  transition: all 0.3s ease;
  flex-shrink: 0;
}

.thumbnail:hover {
  border-color: #1db954;
  transform: scale(1.05);
}

.thumbnail.active {
  border-color: #1db954;
  opacity: 1;
}

.thumbnail:not(.active) {
  opacity: 0.7;
}

/* 基本信息CARD样式 */
.info-card .card-content {
  padding: 0;
}

.spot-name-row {
  padding: 20px 20px 0;
  text-align: center;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.spot-name {
  margin: 0 0 16px 0;
  font-size: 24px;
  font-weight: 600;
  color: #ffffff;
}

.info-grid-4-col {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16px;
  padding: 20px;
}

.info-item {
  display: flex;
  flex-direction: row;
  align-items: center;
  gap: 4px;
}

.info-label {
  font-size: 12px;
  color: #b3b3b3;
  font-weight: 500;
}

.info-value {
  font-size: 14px;
  color: #ffffff;
  font-weight: 500;
}

.status-green {
  color: #1db954;
}

.status-orange {
  color: #ff6666;
}

/* 分类信息CARD样式 */
.category-card .card-content {
  padding: 20px;
}

.category-item {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.category-item:last-child {
  margin-bottom: 0;
}

.category-label {
  font-size: 14px;
  color: #b3b3b3;
  font-weight: 600;
  margin-right: 8px;
  min-width: 80px;
}

.category-value {
  font-size: 14px;
  color: #1ed760;
  font-weight: 500;
}

/* 描述CARD样式 */
.description-card .card-content {
  padding: 20px;
}

.description-text {
  margin: 0;
  font-size: 14px;
  color: #ffffff;
  line-height: 1.6;
  white-space: pre-wrap;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .info-grid-4-col {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 480px) {
  .info-grid-4-col {
    grid-template-columns: 1fr;
  }
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}
</style>